package com.ahuan.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.testng.annotations.Test;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtUtil {

    /**
     * token过期时间：30分钟 ,30 * 60 * 1000毫秒
     */
    private static final long EXPIRE_TIME = 30 * 60 * 1000 * 10;


    /**
     * token秘钥
     */
    private static String TOKEN_SECRET;

    @Autowired
    public JwtUtil(Environment env) {
        TOKEN_SECRET = env.getProperty("jwt.auth.secret");
    }

    /**
     * 生成签名，30分钟过期
     *
     * @param username  用户名
     * @param loginTime 登录时间
     * @return 生成的token
     */
    public static String sign(String id, String username, String loginTime) {
        try {
            // 设置过期时间
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            // 私钥和加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            // 设置头部信息
            Map<String, Object> header = new HashMap<>(2);
            header.put("Type", "Jwt");
            header.put("alg", "HS256");
            // 返回token字符串
            return JWT.create()
                    .withHeader(header)
                    .withClaim("userName", username)
                    .withClaim("loginTime", loginTime)
                    .withClaim("userId", id)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 解析 JWT
    public static DecodedJWT decodeToken(String token) {
        try {
            return JWT.decode(token);
        } catch (JWTDecodeException e) {
            // Invalid token
            e.printStackTrace();
            return null;
        }
    }


    // 验证 JWT
    public static boolean verifyToken(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWT.require(algorithm).build().verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }


    //测试
    public static void main(String[] args) {
        //验证
//        String token = JwtUtil.sign("ahuan","2024-4-5");
//        System.out.println(token);
//        boolean ret = JwtUtil.verifyToken("eyJhbGciOiJIUzI1NiIsIlR5cGUiOiJKd3QiLCJ0eXAiOiJKV1QifQ.eyJsb2dpblRpbWUiOiIyMDI0LTQtNSIsImxvZ2luTmFtZSI6ImFodWFuIiwiZXhwIjoxNzEyMzE3NjA4fQ.APAMHsIICKSgSMxH3lugzcjeoUYUWh1mQwxtLxK2Cl4");
//        System.out.println(ret);
        //逆向获取声明
        DecodedJWT decodedJWT = JwtUtil.decodeToken("eyJhbGciOiJIUzI1NiIsIlR5cGUiOiJKd3QiLCJ0eXAiOiJKV1QifQ.eyJsb2dpblRpbWUiOiJTYXQgQXByIDA2IDE0OjAzOjQ0IENTVCAyMDI0IiwibG9naW5OYW1lIjoiYWh1YW4iLCJleHAiOjE3MTIzODUyMjR9.GzRlLmwlWdwVOVQPQdyLGyUQvCWCUcAjhFBmWYPcxic");
        System.out.println(decodedJWT.getClaim("loginName").asString());
    }
}
